package taper.controller.wcs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import taper.controller.plc.TaperAdjustProcessor;
import taper.controller.plc.TaperAverage;
import util.Activity;
import util.ErrorMessage;
import util.PropertiesLoader;
import util.common;

public class TaperAverageExcelProcessor {
	private static final Logger log = Logger.getLogger(TaperAverageExcelProcessor.class);
	private final String taperAverageFileName = "TaperAverage.xls";

	public void startWCSTaperAverage() {
		new Thread(new Runnable() {
			public void run() {
				
				
				while (true) {
					File dir = new File(PropertiesLoader.getWcsFileDir());
					
					if(!dir.exists()){
						log.info(dir.getName()+" not exist");
						if(dir.mkdir()){
							log.info(" Successful create"+dir.getName());
						}
					}

					FilenameFilter filter = new FilenameFilter() {
						public boolean accept(File dir, String name) {
							return name.endsWith(taperAverageFileName);
						}
					};
					String[] files = dir.list(filter);

                    processFiles(files);
                    	
                    }
					
				}

			private void processFiles(String[] files) {
				
				File taperAverageFile = null;
				InputStream inp = null;
				
				ArrayList filesArrayList = new ArrayList();
				for (String file : files) {
					filesArrayList.add(file);
				}

				Collections.sort(filesArrayList);

				for (int i = 0; i < filesArrayList.size(); i++) {
					String fileName = (String) filesArrayList.get(i);
					try {
						taperAverageFile = new File(PropertiesLoader.getWcsFileDir()+"\\" + fileName);

						if (taperAverageFile.exists()) {
							log.info("TaperAverage File exist");
							Thread.sleep(PropertiesLoader.getTaperAverageInterval());

							inp = new FileInputStream(taperAverageFile);

							Workbook wb = WorkbookFactory.create(inp);

							Sheet sheet = wb.getSheetAt(0);

							Iterator rows = sheet.rowIterator();

							if (rows.hasNext()) {
								rows.next();
							}

							while (rows.hasNext()) {
								Row row = (Row) rows.next();
								Cell cell0 = row.getCell(0);

								if (cell0 == null) {
									log.info("cell0 is null, break from loop");
									break;
								}
								if (cell0.getStringCellValue().equals("")) {
									log.info("cell0 is empty content, break from loop");
									break;
								}

								Cell cell1 = row.getCell(1);
								Cell cell9 = row.getCell(9);

								String taperID = cell0.getStringCellValue().trim();

								String lotID = common.getAsAlphaNumeric(cell1);

								if(cell9 == null){
									continue;
								}
								
								double averageValue = cell9.getNumericCellValue();
								
								log.info("Taper Average value : taperID:"+taperID+" lotID:"+lotID+" averageValue:"+averageValue);
								Activity.log("Completed Taper Average "+lotID+","+taperID+",averageValue="+averageValue, PropertiesLoader.getSystemUser(), "Data auto received from WCS Taper Average");
								TaperAdjustProcessor.taperAverageQueue.put(new TaperAverage(taperID, averageValue, lotID));
							}

							inp.close();
							taperAverageFile.delete();
							
						}

						Thread.sleep(PropertiesLoader.getTaperAverageInterval());
					} catch (Exception e) {
						log.error("startWCSTaperAverage",e);

						if (inp != null) {
							try {
								inp.close();
							} catch (Exception ie) {
								log.error("startWCSTaperAverage",e);
							}
						}
						if ((taperAverageFile == null) || (!taperAverageFile.exists()))
							continue;
						File errorFolder = new File("C:\\wcsdata\\error\\");
						if (!errorFolder.exists()) {
							errorFolder.mkdirs();
						}

						String errorFileName = "C:\\wcsdata\\error\\TaperAverage_error_" + fileName;

						common.copyfile(taperAverageFile, new File(errorFileName));
						taperAverageFile.delete();
						
						Activity.log("Error occur while reading TaperAverage.xls file", PropertiesLoader.getSystemUser(), "The file renamed to "+errorFileName+ " for checking.");
						ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, true, "Error occur while reading TaperAverage.xls file", " The file renamed to "+errorFileName+ " for checking.");
						
					}
				}
			}
			
		}).start();
	}

}
